[[...path]].page.tsx 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616
  1. import React, { useEffect } from 'react';
  2. import EventEmitter from 'events';
  3. import {
  4. IDataWithMeta, IPageInfoForEntity, IPagePopulatedToShowRevision, isClient, isIPageInfoForEntity, IUser, IUserHasId, pagePathUtils, pathUtils,
  5. } from '@growi/core';
  6. import ExtensibleCustomError from 'extensible-custom-error';
  7. import { model as mongooseModel } from 'mongoose';
  8. import {
  9. NextPage, GetServerSideProps, GetServerSidePropsContext,
  10. } from 'next';
  11. import { serverSideTranslations } from 'next-i18next/serverSideTranslations';
  12. import dynamic from 'next/dynamic';
  13. import Head from 'next/head';
  14. import { useRouter } from 'next/router';
  15. import superjson from 'superjson';
  16. import { Comments } from '~/components/Comments';
  17. import { RecentlyCreatedIcon } from '~/components/Icons/RecentlyCreatedIcon';
  18. import { PageAlerts } from '~/components/PageAlert/PageAlerts';
  19. // import { useTranslation } from '~/i18n';
  20. import { PageContentFooter } from '~/components/PageContentFooter';
  21. import { BookmarkList } from '~/components/PageList/BookmarkList';
  22. import { RecentCreated } from '~/components/RecentCreated/RecentCreated';
  23. import { CrowiRequest } from '~/interfaces/crowi-request';
  24. // import { renderScriptTagByName, renderHighlightJsStyleTag } from '~/service/cdn-resources-loader';
  25. // import { useIndentSize } from '~/stores/editor';
  26. // import { useRendererSettings } from '~/stores/renderer';
  27. // import { EditorMode, useEditorMode, useIsMobile } from '~/stores/ui';
  28. import { EditorConfig } from '~/interfaces/editor-settings';
  29. import { CustomWindow } from '~/interfaces/global';
  30. import { RendererConfig } from '~/interfaces/services/renderer';
  31. import { ISidebarConfig } from '~/interfaces/sidebar-config';
  32. import { IUserUISettings } from '~/interfaces/user-ui-settings';
  33. import { PageModel, PageDocument } from '~/server/models/page';
  34. import { PageRedirectModel } from '~/server/models/page-redirect';
  35. import { UserUISettingsModel } from '~/server/models/user-ui-settings';
  36. import { useSWRxCurrentPage, useSWRxIsGrantNormalized, useSWRxPageInfo } from '~/stores/page';
  37. import { useRedirectFrom } from '~/stores/page-redirect';
  38. import {
  39. usePreferDrawerModeByUser, usePreferDrawerModeOnEditByUser, useSidebarCollapsed, useCurrentSidebarContents, useCurrentProductNavWidth, useSelectedGrant,
  40. } from '~/stores/ui';
  41. import loggerFactory from '~/utils/logger';
  42. // import { isUserPage, isTrashPage, isSharedPage } from '~/utils/path-utils';
  43. // import GrowiSubNavigation from '../client/js/components/Navbar/GrowiSubNavigation';
  44. // import GrowiSubNavigationSwitcher from '../client/js/components/Navbar/GrowiSubNavigationSwitcher';
  45. import { DescendantsPageListModal } from '../components/DescendantsPageListModal';
  46. import { BasicLayout } from '../components/Layout/BasicLayout';
  47. import GrowiContextualSubNavigation from '../components/Navbar/GrowiContextualSubNavigation';
  48. import DisplaySwitcher from '../components/Page/DisplaySwitcher';
  49. // import { serializeUserSecurely } from '../server/models/serializers/user-serializer';
  50. // import PageStatusAlert from '../client/js/components/PageStatusAlert';
  51. import {
  52. useCurrentUser, useCurrentPagePath,
  53. useIsLatestRevision,
  54. useIsForbidden, useIsNotFound, useIsTrashPage, useIsSharedUser,
  55. useIsEnabledStaleNotification, useIsIdenticalPath,
  56. useIsSearchServiceConfigured, useIsSearchServiceReachable, useDisableLinkSharing,
  57. useHackmdUri,
  58. useIsAclEnabled, useIsUserPage, useIsNotCreatable,
  59. useCsrfToken, useIsSearchScopeChildrenAsDefault, useCurrentPageId, useCurrentPathname,
  60. useIsSlackConfigured, useRendererConfig, useEditingMarkdown,
  61. useEditorConfig, useIsAllReplyShown, useIsUploadableFile, useIsUploadableImage,
  62. } from '../stores/context';
  63. import {
  64. CommonProps, getNextI18NextConfig, getServerSideCommonProps, useCustomTitle,
  65. } from './utils/commons';
  66. // import { useCurrentPageSWR } from '../stores/page';
  67. const NotCreatablePage = dynamic(() => import('../components/NotCreatablePage').then(mod => mod.NotCreatablePage), { ssr: false });
  68. const ForbiddenPage = dynamic(() => import('../components/ForbiddenPage'), { ssr: false });
  69. const UnsavedAlertDialog = dynamic(() => import('./UnsavedAlertDialog'), { ssr: false });
  70. const GrowiSubNavigationSwitcher = dynamic(() => import('../components/Navbar/GrowiSubNavigationSwitcher'), { ssr: false });
  71. const logger = loggerFactory('growi:pages:all');
  72. const {
  73. isPermalink: _isPermalink, isUsersHomePage, isTrashPage: _isTrashPage, isUserPage, isCreatablePage,
  74. } = pagePathUtils;
  75. const { removeHeadingSlash } = pathUtils;
  76. type IPageToShowRevisionWithMeta = IDataWithMeta<IPagePopulatedToShowRevision & PageDocument, IPageInfoForEntity>;
  77. type IPageToShowRevisionWithMetaSerialized = IDataWithMeta<string, string>;
  78. superjson.registerCustom<IPageToShowRevisionWithMeta, IPageToShowRevisionWithMetaSerialized>(
  79. {
  80. isApplicable: (v): v is IPageToShowRevisionWithMeta => {
  81. return v?.data != null
  82. && v?.data.toObject != null
  83. && v?.meta != null
  84. && isIPageInfoForEntity(v.meta);
  85. },
  86. serialize: (v) => {
  87. return {
  88. data: superjson.stringify(v.data.toObject()),
  89. meta: superjson.stringify(v.meta),
  90. };
  91. },
  92. deserialize: (v) => {
  93. return {
  94. data: superjson.parse(v.data),
  95. meta: v.meta != null ? superjson.parse(v.meta) : undefined,
  96. };
  97. },
  98. },
  99. 'IPageToShowRevisionWithMetaTransformer',
  100. );
  101. const IdenticalPathPage = (): JSX.Element => {
  102. const IdenticalPathPage = dynamic(() => import('../components/IdenticalPathPage').then(mod => mod.IdenticalPathPage), { ssr: false });
  103. return <IdenticalPathPage />;
  104. };
  105. const PutbackPageModal = (): JSX.Element => {
  106. const PutbackPageModal = dynamic(() => import('../components/PutbackPageModal'), { ssr: false });
  107. return <PutbackPageModal />;
  108. };
  109. type Props = CommonProps & {
  110. currentUser: IUser,
  111. pageWithMeta: IPageToShowRevisionWithMeta,
  112. // pageUser?: any,
  113. redirectFrom?: string;
  114. // shareLinkId?: string;
  115. isLatestRevision?: boolean
  116. isIdenticalPathPage?: boolean,
  117. isForbidden: boolean,
  118. isNotFound: boolean,
  119. IsNotCreatable: boolean,
  120. // isAbleToDeleteCompletely: boolean,
  121. isSearchServiceConfigured: boolean,
  122. isSearchServiceReachable: boolean,
  123. isSearchScopeChildrenAsDefault: boolean,
  124. isSlackConfigured: boolean,
  125. // isMailerSetup: boolean,
  126. isAclEnabled: boolean,
  127. // hasSlackConfig: boolean,
  128. // drawioUri: string,
  129. hackmdUri: string,
  130. // mathJax: string,
  131. // noCdn: string,
  132. // highlightJsStyle: string,
  133. isAllReplyShown: boolean,
  134. // isContainerFluid: boolean,
  135. editorConfig: EditorConfig,
  136. isEnabledStaleNotification: boolean,
  137. // isEnabledLinebreaks: boolean,
  138. // isEnabledLinebreaksInComments: boolean,
  139. // adminPreferredIndentSize: number,
  140. // isIndentSizeForced: boolean,
  141. disableLinkSharing: boolean,
  142. rendererConfig: RendererConfig,
  143. // UI
  144. userUISettings?: IUserUISettings
  145. // Sidebar
  146. sidebarConfig: ISidebarConfig,
  147. };
  148. const GrowiPage: NextPage<Props> = (props: Props) => {
  149. // const { t } = useTranslation();
  150. const router = useRouter();
  151. const { data: currentUser } = useCurrentUser(props.currentUser ?? null);
  152. // register global EventEmitter
  153. if (isClient()) {
  154. (window as CustomWindow).globalEmitter = new EventEmitter();
  155. }
  156. // commons
  157. useEditorConfig(props.editorConfig);
  158. useCsrfToken(props.csrfToken);
  159. // UserUISettings
  160. usePreferDrawerModeByUser(props.userUISettings?.preferDrawerModeByUser ?? props.sidebarConfig.isSidebarDrawerMode);
  161. usePreferDrawerModeOnEditByUser(props.userUISettings?.preferDrawerModeOnEditByUser);
  162. useSidebarCollapsed(props.userUISettings?.isSidebarCollapsed ?? props.sidebarConfig.isSidebarClosedAtDockMode);
  163. useCurrentSidebarContents(props.userUISettings?.currentSidebarContents);
  164. useCurrentProductNavWidth(props.userUISettings?.currentProductNavWidth);
  165. // page
  166. useIsLatestRevision(props.isLatestRevision);
  167. // useOwnerOfCurrentPage(props.pageUser != null ? JSON.parse(props.pageUser) : null);
  168. useIsForbidden(props.isForbidden);
  169. useIsNotFound(props.isNotFound);
  170. useIsNotCreatable(props.IsNotCreatable);
  171. useRedirectFrom(props.redirectFrom);
  172. // useIsTrashPage(_isTrashPage(props.currentPagePath));
  173. // useShared();
  174. // useShareLinkId(props.shareLinkId);
  175. useIsSharedUser(false); // this page cann't be routed for '/share'
  176. useIsIdenticalPath(false); // TODO: need to initialize from props
  177. // useIsAbleToDeleteCompletely(props.isAbleToDeleteCompletely);
  178. useIsEnabledStaleNotification(props.isEnabledStaleNotification);
  179. useIsSearchServiceConfigured(props.isSearchServiceConfigured);
  180. useIsSearchServiceReachable(props.isSearchServiceReachable);
  181. useIsSearchScopeChildrenAsDefault(props.isSearchScopeChildrenAsDefault);
  182. useIsSlackConfigured(props.isSlackConfigured);
  183. // useIsMailerSetup(props.isMailerSetup);
  184. useIsAclEnabled(props.isAclEnabled);
  185. // useHasSlackConfig(props.hasSlackConfig);
  186. // useDrawioUri(props.drawioUri);
  187. useHackmdUri(props.hackmdUri);
  188. // useMathJax(props.mathJax);
  189. // useNoCdn(props.noCdn);
  190. // useIndentSize(props.adminPreferredIndentSize);
  191. useDisableLinkSharing(props.disableLinkSharing);
  192. useRendererConfig(props.rendererConfig);
  193. // useRendererSettings(props.rendererSettingsStr != null ? JSON.parse(props.rendererSettingsStr) : undefined);
  194. // useGrowiRendererConfig(props.growiRendererConfigStr != null ? JSON.parse(props.growiRendererConfigStr) : undefined);
  195. useIsAllReplyShown(props.isAllReplyShown);
  196. useIsUploadableFile(props.editorConfig.upload.isUploadableFile);
  197. useIsUploadableImage(props.editorConfig.upload.isUploadableImage);
  198. // const { data: editorMode } = useEditorMode();
  199. const { pageWithMeta, userUISettings } = props;
  200. let shouldRenderPutbackPageModal = false;
  201. if (pageWithMeta != null) {
  202. shouldRenderPutbackPageModal = _isTrashPage(pageWithMeta.data.path);
  203. }
  204. const pageId = pageWithMeta?.data._id;
  205. useCurrentPageId(pageId);
  206. useSWRxCurrentPage(undefined, pageWithMeta?.data); // store initial data
  207. useSWRxPageInfo(pageId, undefined, pageWithMeta?.meta); // store initial data
  208. useIsTrashPage(_isTrashPage(pageWithMeta?.data.path ?? ''));
  209. useIsUserPage(isUserPage(pageWithMeta?.data.path ?? ''));
  210. useIsNotCreatable(props.isForbidden || !isCreatablePage(pageWithMeta?.data.path ?? '')); // TODO: need to include props.isIdentical
  211. useCurrentPagePath(pageWithMeta?.data.path);
  212. useCurrentPathname(props.currentPathname);
  213. useEditingMarkdown(pageWithMeta?.data.revision?.body);
  214. const { data: grantData } = useSWRxIsGrantNormalized(pageId);
  215. const { mutate: mutateSelectedGrant } = useSelectedGrant();
  216. // sync grant data
  217. useEffect(() => {
  218. mutateSelectedGrant(grantData?.grantData.currentPageGrant);
  219. }, [grantData?.grantData.currentPageGrant, mutateSelectedGrant]);
  220. // sync pathname by Shallow Routing https://nextjs.org/docs/routing/shallow-routing
  221. useEffect(() => {
  222. const decodedURI = decodeURI(window.location.pathname);
  223. if (isClient() && decodedURI !== props.currentPathname) {
  224. router.replace(props.currentPathname, undefined, { shallow: true });
  225. }
  226. }, [props.currentPathname, router]);
  227. const classNames: string[] = [];
  228. // switch (editorMode) {
  229. // case EditorMode.Editor:
  230. // classNames.push('on-edit', 'builtin-editor');
  231. // break;
  232. // case EditorMode.HackMD:
  233. // classNames.push('on-edit', 'hackmd');
  234. // break;
  235. // }
  236. // if (page == null) {
  237. // classNames.push('not-found-page');
  238. // }
  239. return (
  240. <>
  241. <Head>
  242. {/*
  243. {renderScriptTagByName('drawio-viewer')}
  244. {renderScriptTagByName('mathjax')}
  245. {renderScriptTagByName('highlight-addons')}
  246. {renderHighlightJsStyleTag(props.highlightJsStyle)}
  247. */}
  248. </Head>
  249. {/* <BasicLayout title={useCustomTitle(props, t('GROWI'))} className={classNames.join(' ')}> */}
  250. <BasicLayout title={useCustomTitle(props, 'GROWI')} className={classNames.join(' ')} expandContainer={props.isContainerFluid}>
  251. <header className="py-0 position-relative">
  252. <GrowiContextualSubNavigation isLinkSharingDisabled={props.disableLinkSharing} />
  253. </header>
  254. <div className="d-edit-none">
  255. <GrowiSubNavigationSwitcher />
  256. </div>
  257. <div id="grw-subnav-sticky-trigger" className="sticky-top"></div>
  258. <div id="grw-fav-sticky-trigger" className="sticky-top"></div>
  259. <div id="main" className={`main ${isUsersHomePage(props.currentPathname) && 'user-page'}`}>
  260. <div id="content-main" className="content-main grw-container-convertible">
  261. <div className="row">
  262. <div className="col">
  263. { props.isIdenticalPathPage && <IdenticalPathPage /> }
  264. { !props.isIdenticalPathPage && (
  265. <>
  266. <PageAlerts />
  267. { props.isForbidden && <ForbiddenPage /> }
  268. { props.IsNotCreatable && <NotCreatablePage />}
  269. { !props.isForbidden && !props.IsNotCreatable && <DisplaySwitcher />}
  270. {/* <DisplaySwitcher /> */}
  271. <div id="page-editor-navbar-bottom-container" className="d-none d-edit-block"></div>
  272. {/* <PageStatusAlert /> */}
  273. </>
  274. ) }
  275. </div>
  276. </div>
  277. {/* <div className="col-xl-2 col-lg-3 d-none d-lg-block revision-toc-container">
  278. <div id="revision-toc" className="revision-toc mt-3 sps sps--abv" data-sps-offset="123">
  279. <div id="revision-toc-content" className="revision-toc-content"></div>
  280. </div>
  281. </div> */}
  282. </div>
  283. </div>
  284. {/* TODO: Check CSS import */}
  285. <footer className="footer d-edit-none">
  286. {/* TODO: Enable page_list.html */}
  287. {/* TODO: Enable isIdenticalPathPage or useIdenticalPath */}
  288. {/* { !props.isIdenticalPathPage && ( */}
  289. <Comments pageId={pageId} />
  290. {/* )} */}
  291. {/* TODO: Create UsersHomePageFooter conponent */}
  292. { (pageWithMeta != null && isUsersHomePage(pageWithMeta?.data.path)) && (
  293. <div className="container-lg user-page-footer py-5">
  294. <div className="grw-user-page-list-m d-edit-none">
  295. <h2 id="bookmarks-list" className="grw-user-page-header border-bottom pb-2 mb-3">
  296. <i style={{ fontSize: '1.3em' }} className="fa fa-fw fa-bookmark-o"></i>
  297. Bookmarks
  298. </h2>
  299. <div id="user-bookmark-list" className="page-list">
  300. <div className="page-list-container">
  301. <BookmarkList userId={pageWithMeta?.data.creator._id} />
  302. </div>
  303. </div>
  304. </div>
  305. <div className="grw-user-page-list-m mt-5 d-edit-none">
  306. <h2 id="recently-created-list" className="grw-user-page-header border-bottom pb-2 mb-3">
  307. <i id="recent-created-icon" className="mr-1">
  308. <RecentlyCreatedIcon />
  309. </i>
  310. Recently Created
  311. </h2>
  312. <div id="user-created-list" className="page-list">
  313. <div className="page-list-container">
  314. <RecentCreated userId={pageWithMeta?.data.creator._id} />
  315. </div>
  316. </div>
  317. </div>
  318. </div>
  319. )}
  320. <PageContentFooter />
  321. </footer>
  322. <UnsavedAlertDialog />
  323. <DescendantsPageListModal />
  324. {shouldRenderPutbackPageModal && <PutbackPageModal />}
  325. </BasicLayout>
  326. </>
  327. );
  328. };
  329. function getPageIdFromPathname(currentPathname: string): string | null {
  330. return _isPermalink(currentPathname) ? removeHeadingSlash(currentPathname) : null;
  331. }
  332. class MultiplePagesHitsError extends ExtensibleCustomError {
  333. pagePath: string;
  334. constructor(pagePath: string) {
  335. super(`MultiplePagesHitsError occured by '${pagePath}'`);
  336. this.pagePath = pagePath;
  337. }
  338. }
  339. async function injectPageData(context: GetServerSidePropsContext, props: Props): Promise<void> {
  340. const req: CrowiRequest = context.req as CrowiRequest;
  341. const { crowi } = req;
  342. const { revisionId } = req.query;
  343. const Page = crowi.model('Page') as PageModel;
  344. const PageRedirect = mongooseModel('PageRedirect') as PageRedirectModel;
  345. const { pageService } = crowi;
  346. let currentPathname = props.currentPathname;
  347. const pageId = getPageIdFromPathname(currentPathname);
  348. const isPermalink = _isPermalink(currentPathname);
  349. const { user } = req;
  350. if (!isPermalink) {
  351. // check redirects
  352. const chains = await PageRedirect.retrievePageRedirectEndpoints(currentPathname);
  353. if (chains != null) {
  354. // overwrite currentPathname
  355. currentPathname = chains.end.toPath;
  356. props.currentPathname = currentPathname;
  357. // set redirectFrom
  358. props.redirectFrom = chains.start.fromPath;
  359. }
  360. // check whether the specified page path hits to multiple pages
  361. const count = await Page.countByPathAndViewer(currentPathname, user, null, true);
  362. if (count > 1) {
  363. throw new MultiplePagesHitsError(currentPathname);
  364. }
  365. }
  366. const pageWithMeta: IPageToShowRevisionWithMeta = await pageService.findPageAndMetaDataByViewer(pageId, currentPathname, user, true); // includeEmpty = true, isSharedPage = false
  367. const page = pageWithMeta?.data as unknown as PageDocument;
  368. // populate & check if the revision is latest
  369. if (page != null) {
  370. page.initLatestRevisionField(revisionId);
  371. await page.populateDataToShowRevision();
  372. props.isLatestRevision = page.isLatestRevision();
  373. }
  374. props.pageWithMeta = pageWithMeta;
  375. }
  376. async function injectUserUISettings(context: GetServerSidePropsContext, props: Props): Promise<void> {
  377. const req = context.req as CrowiRequest<IUserHasId & any>;
  378. const { user } = req;
  379. const UserUISettings = mongooseModel('UserUISettings') as UserUISettingsModel;
  380. const userUISettings = user == null ? null : await UserUISettings.findOne({ user: user._id }).exec();
  381. if (userUISettings != null) {
  382. props.userUISettings = userUISettings.toObject();
  383. }
  384. }
  385. async function injectRoutingInformation(context: GetServerSidePropsContext, props: Props): Promise<void> {
  386. const req: CrowiRequest = context.req as CrowiRequest;
  387. const { crowi } = req;
  388. const Page = crowi.model('Page') as PageModel;
  389. const { currentPathname } = props;
  390. const pageId = getPageIdFromPathname(currentPathname);
  391. const isPermalink = _isPermalink(currentPathname);
  392. const page = props.pageWithMeta?.data;
  393. if (props.isIdenticalPathPage) {
  394. // TBD
  395. }
  396. else if (page == null) {
  397. props.isNotFound = true;
  398. props.IsNotCreatable = !isCreatablePage(currentPathname);
  399. // check the page is forbidden or just does not exist.
  400. const count = isPermalink ? await Page.count({ _id: pageId }) : await Page.count({ path: currentPathname });
  401. props.isForbidden = count > 0;
  402. }
  403. else {
  404. props.isNotFound = page.isEmpty;
  405. // /62a88db47fed8b2d94f30000 ==> /path/to/page
  406. if (isPermalink && page.isEmpty) {
  407. props.currentPathname = page.path;
  408. }
  409. // /path/to/page ==> /62a88db47fed8b2d94f30000
  410. if (!isPermalink && !page.isEmpty) {
  411. const isToppage = pagePathUtils.isTopPage(props.currentPathname);
  412. if (!isToppage) {
  413. props.currentPathname = `/${page._id}`;
  414. }
  415. }
  416. }
  417. }
  418. // async function injectPageUserInformation(context: GetServerSidePropsContext, props: Props): Promise<void> {
  419. // const req: CrowiRequest = context.req as CrowiRequest;
  420. // const { crowi } = req;
  421. // const UserModel = crowi.model('User');
  422. // if (isUserPage(props.currentPagePath)) {
  423. // const user = await UserModel.findUserByUsername(UserModel.getUsernameByPath(props.currentPagePath));
  424. // if (user != null) {
  425. // props.pageUser = JSON.stringify(user.toObject());
  426. // }
  427. // }
  428. // }
  429. function injectServerConfigurations(context: GetServerSidePropsContext, props: Props): void {
  430. const req: CrowiRequest = context.req as CrowiRequest;
  431. const { crowi } = req;
  432. const {
  433. appService, searchService, configManager, aclService, slackNotificationService, mailService,
  434. } = crowi;
  435. props.isSearchServiceConfigured = searchService.isConfigured;
  436. props.isSearchServiceReachable = searchService.isReachable;
  437. props.isSearchScopeChildrenAsDefault = configManager.getConfig('crowi', 'customize:isSearchScopeChildrenAsDefault');
  438. props.isSlackConfigured = crowi.slackIntegrationService.isSlackConfigured;
  439. // props.isMailerSetup = mailService.isMailerSetup;
  440. props.isAclEnabled = aclService.isAclEnabled();
  441. // props.hasSlackConfig = slackNotificationService.hasSlackConfig();
  442. // props.drawioUri = configManager.getConfig('crowi', 'app:drawioUri');
  443. props.hackmdUri = configManager.getConfig('crowi', 'app:hackmdUri');
  444. // props.mathJax = configManager.getConfig('crowi', 'app:mathJax');
  445. // props.noCdn = configManager.getConfig('crowi', 'app:noCdn');
  446. // props.highlightJsStyle = configManager.getConfig('crowi', 'customize:highlightJsStyle');
  447. props.isAllReplyShown = configManager.getConfig('crowi', 'customize:isAllReplyShown');
  448. // props.isContainerFluid = configManager.getConfig('crowi', 'customize:isContainerFluid');
  449. props.isEnabledStaleNotification = configManager.getConfig('crowi', 'customize:isEnabledStaleNotification');
  450. // props.isEnabledLinebreaks = configManager.getConfig('markdown', 'markdown:isEnabledLinebreaks');
  451. // props.isEnabledLinebreaksInComments = configManager.getConfig('markdown', 'markdown:isEnabledLinebreaksInComments');
  452. props.disableLinkSharing = configManager.getConfig('crowi', 'security:disableLinkSharing');
  453. props.editorConfig = {
  454. upload: {
  455. isUploadableFile: crowi.fileUploadService.getFileUploadEnabled(),
  456. isUploadableImage: crowi.fileUploadService.getIsUploadable(),
  457. },
  458. };
  459. // props.adminPreferredIndentSize = configManager.getConfig('markdown', 'markdown:adminPreferredIndentSize');
  460. // props.isIndentSizeForced = configManager.getConfig('markdown', 'markdown:isIndentSizeForced');
  461. props.rendererConfig = {
  462. isEnabledLinebreaks: configManager.getConfig('markdown', 'markdown:isEnabledLinebreaks'),
  463. isEnabledLinebreaksInComments: configManager.getConfig('markdown', 'markdown:isEnabledLinebreaksInComments'),
  464. adminPreferredIndentSize: configManager.getConfig('markdown', 'markdown:adminPreferredIndentSize'),
  465. isIndentSizeForced: configManager.getConfig('markdown', 'markdown:isIndentSizeForced'),
  466. plantumlUri: process.env.PLANTUML_URI ?? null,
  467. blockdiagUri: process.env.BLOCKDIAG_URI ?? null,
  468. // XSS Options
  469. isEnabledXssPrevention: configManager.getConfig('markdown', 'markdown:xss:isEnabledPrevention'),
  470. attrWhiteList: crowi.xssService.getAttrWhiteList(),
  471. tagWhiteList: crowi.xssService.getTagWhiteList(),
  472. highlightJsStyleBorder: crowi.configManager.getConfig('crowi', 'customize:highlightJsStyleBorder'),
  473. };
  474. props.sidebarConfig = {
  475. isSidebarDrawerMode: configManager.getConfig('crowi', 'customize:isSidebarDrawerMode'),
  476. isSidebarClosedAtDockMode: configManager.getConfig('crowi', 'customize:isSidebarClosedAtDockMode'),
  477. };
  478. }
  479. /**
  480. * for Server Side Translations
  481. * @param context
  482. * @param props
  483. * @param namespacesRequired
  484. */
  485. async function injectNextI18NextConfigurations(context: GetServerSidePropsContext, props: Props, namespacesRequired?: string[] | undefined): Promise<void> {
  486. const nextI18NextConfig = await getNextI18NextConfig(serverSideTranslations, context, namespacesRequired);
  487. props._nextI18Next = nextI18NextConfig._nextI18Next;
  488. }
  489. export const getServerSideProps: GetServerSideProps = async(context: GetServerSidePropsContext) => {
  490. const req = context.req as CrowiRequest<IUserHasId & any>;
  491. const { user } = req;
  492. const result = await getServerSideCommonProps(context);
  493. // check for presence
  494. // see: https://github.com/vercel/next.js/issues/19271#issuecomment-730006862
  495. if (!('props' in result)) {
  496. throw new Error('invalid getSSP result');
  497. }
  498. const props: Props = result.props as Props;
  499. if (user != null) {
  500. props.currentUser = user.toObject();
  501. }
  502. try {
  503. await injectPageData(context, props);
  504. }
  505. catch (err) {
  506. if (err instanceof MultiplePagesHitsError) {
  507. props.isIdenticalPathPage = true;
  508. }
  509. else {
  510. throw err;
  511. }
  512. }
  513. await injectUserUISettings(context, props);
  514. await injectRoutingInformation(context, props);
  515. injectServerConfigurations(context, props);
  516. await injectNextI18NextConfigurations(context, props, ['translation']);
  517. return {
  518. props,
  519. };
  520. };
  521. export default GrowiPage;